<template>
  <el-container>
    <div class="c1">
      <!-- <el-button type="primary" icon="el-icon-search">搜索</el-button> -->
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="adddept"
        >新增</el-button
      >
      <el-button
        :loading="downloadLoading"
        size="mini"
        class="dBtn"
        type="warning"
        icon="el-icon-download"
        @click="download"
        >导出</el-button
      >
      <el-form :inline="true" :model="searchData" class="demo-form-inline s1">
        <el-form-item>
          <el-input
            class="search_inp"
            v-model="searchData.name"
            placeholder="输入内容查询"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="searchBtn(searchData)"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-refresh-left"
            @click="searchrestBtn(searchData)"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card class="c2">
      <el-table
        :data="tableData"
        style="width: 100%"
        max-height="400"
        align="center"
        stripe
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>

        <el-table-column prop="name" label="部门名"> </el-table-column>
        <el-table-column prop="level" label="部门等级"> </el-table-column>

        <el-table-column prop="status" label="部门状态">
          <template v-slot="prop">
            <el-switch
              @change="changeSwitch(prop.row.status, prop.row.id)"
              v-model="prop.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="linkMan" label="联系人"> </el-table-column>
        <el-table-column prop="linkPhone" label="联系电话"> </el-table-column>

        <el-table-column width="150" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column> </el-table
    ></el-card>
    <el-footer v-if="searchToggle">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.pageNum.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="this.pageNum.perPage_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.pageNum.total"
      >
      </el-pagination>
    </el-footer>
    <!-- 新增部门对话框 start -->

    <el-dialog
      title="部门新增"
      ref="ruleForm"
      :rules="rules"
      :visible.sync="adddeptDialogVisible"
      width="50%"
    >
      <el-form
        class="editform"
        label-position="left"
        label-width="80px"
        :model="addData"
        ref="ruleForm"
        :rules="rules"
      >
        <el-form-item label="上级部门">
          <!-- <el-select v-model="addData.pid" placeholder="请选择">
            <el-option value="0" label="顶级部门"></el-option>
            <el-option
              v-for="item in parentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
			<el-cascader
				v-model="addData.pid"
				:options="parentList"
				:show-all-levels="false"
				size="small"
				style="width: 240px;"
			>
			</el-cascader>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addData.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="部门等级" prop="level">
          <el-input v-model="addData.level" placeholder="请输入"></el-input>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-switch
            v-model="addData.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="addData.linkMan" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="linkPhone">
          <el-input v-model="addData.linkPhone" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddeptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adddeptDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增部门对话框 end -->

    <!-- 删除 -->
    <el-dialog title="提示" :visible.sync="deldeptDialogVisible" width="30%">
      确认删除吗?
      <span slot="footer" class="dialog-footer">
        <el-button @click="deldeptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deldeptDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="部门修改"
      :visible.sync="editdeptDialogVisible"
      width="50%"
    >
      <el-form
        class="editform"
        ref="ruleForm2"
        :rules="rules"
        label-position="left"
        label-width="80px"
        :model="deptsForm"
      >
        <el-form-item label="上级部门">
          <!-- <el-select v-model="deptsForm.pid" placeholder="请选择">
            <el-option value="0" label="顶级部门"></el-option>
            <el-option
              v-for="item in parentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
			<el-cascader
				v-model="deptsForm.pid"
				:options="parentList"
				:show-all-levels="false"
				size="small"
				style="width: 240px;"
			>
			</el-cascader>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptsForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="部门等级" prop="level">
          <el-input v-model="deptsForm.level" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScopeList">
          <el-select
            multiple
            v-model="deptsForm.dataScopeList"
            placeholder="请选择"
          >
            <el-option
              v-for="item in tableData1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-switch
            v-model="deptsForm.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="deptsForm.linkMan" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="linkPhone">
          <el-input
            v-model="deptsForm.linkPhone"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdeptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editdeptDialog">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import axios from "../../utils/axios";
// import icons from "./icons";
import eventBus from "../../utils/eventBus";

export default {
  methods: {
    //部门树列表
    getdeptList() {
      let data = {};
      data.isAll = true;
      axios({
        method: "GET",
        url: "/sys/department/tree",
        params: data,
      }).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.parentList = res.data.filter((item) => item.pid == 0);
					this.dealArr(this.parentList)
          this.loading = false;
          // this.pageNum.current = res.data.current;
          // this.pageNum.size = res.data.size;
          // this.pageNum.total = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //部门查询
    getdept(con) {
      axios({
        method: "GET",
        url: "/sys/department",
        params: con,
      }).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.parentList = res.data.records.filter((item) => item.pid == 0);
          this.loading = false;
					this.pageNum.current = res.data.current;
          this.pageNum.size = res.data.size;
          this.pageNum.total = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
    },
		
		/**
		 * 20211115
		 * 递归查找，获取children
		 */
		dealArr(arr) {
			arr.forEach((v) => {
				v.label = v.name
				v.value = v.id
				if (v.children && v.children.length) {
					this.dealArr(v.children)
				}
			})
		},
		
    getdept1() {
      axios({
        method: "GET",
        url: "/sys/department",
      }).then((res) => {
        if (res.code == 200) {
          this.tableData1 = res.data.records;
        }
      });
    },
    //页码
    handleSizeChange(val) {
      this.pageNum.size = val;
      if (this.searchToggle) {
        this.searchData.current = this.pageNum.current;
        this.searchData.size = this.pageNum.size;
        this.getdept(this.searchData);
      } else {
        this.getdeptList();
      }
    },
    handleCurrentChange(val) {
      this.pageNum.current = val;
      if (this.searchToggle) {
        this.searchData.current = this.pageNum.current;
        this.searchData.size = this.pageNum.size;
        this.getdept(this.searchData);
      } else {
        this.getdeptList();
      }
    },
    //添加
    adddept() {
      this.adddeptDialogVisible = true;
    },
    adddeptDialog() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          axios({
            method: "POST",
            url: "/sys/department",
            data: this.addData,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.adddeptDialogVisible = false;
              this.getdeptList(this.pageNum);
            } else {
              console.log(res);
              this.$message.error(res.message);
            }
          });
        } else {
          this.$message.error("内容不完整");
        }
      });
    },

    adddepthandleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    //部门状态
    changeSwitch(con1, con2) {
      let data = {};
      data.id = con2;
      data.status = con1;
      if (con1 == 1) {
        let data = {};
        data.id = con2;
        data.status = con1;

        this.$confirm("此操作将启用该部门", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/department",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("已启用");
                  this.getdeptList()
              } else {
                this.$message.error(res.message);
                  this.getdeptList()
              }
            
            });
          })
          .catch(() => {
             this.getdeptList()
          });
      }
      if (con1 == 0) {
        let data = {};
        data.id = con2;
        data.status = con1;

        this.$confirm("此操作将禁用该部门", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/department",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("已禁用");
                  this.getdeptList()
              } else {
                this.$message.error(res.message);
                  this.getdeptList()
              }
             
            });
          })
          .catch(() => {
              this.getdeptList()
          });
      }
    },
    //查询
    searchBtn(con) {
      this.getdept(con);
      this.searchToggle = true;
    },
    //导出
    download() {
      this.downloadLoading = true;
    },

    //重置
    searchrestBtn() {
      this.searchData.name = "";
      this.getdeptList();
      this.searchToggle = false;
    },
    //删除
    handleDelete(con) {
      this.deldeptDialogVisible = true;

      this.delDate = [];
      this.delDate.push(con);
    },
    deldeptDialog() {
      axios({
        method: "delete",
        url: "/sys/department",

        data: JSON.stringify(this.delDate),
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.deldeptDialogVisible = false;
          this.getdeptList(this.pageNum);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deldepthandleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    //修改
    handleEdit(con) {
      this.editdeptDialogVisible = true;
      this.deptsForm.icon = con.icon;
      this.deptsForm.id = con.id;
      this.deptsForm.isHide = con.isHide;
      this.deptsForm.link = con.link;
      this.deptsForm.name = con.name;
      this.deptsForm.path = con.path;
      this.deptsForm.pid = con.pid;
      this.deptsForm.sort = con.sort;
      this.deptsForm.status = con.status;
      this.deptsForm.type = con.type;
      this.deptsForm.authStr = con.authStr;
    },
    editdeptDialog() {
      this.$refs.ruleForm2.validate((valid) => {
        if (valid) {
          axios({
            method: "PUT",
            url: "/sys/department",
            data: this.deptsForm,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.editdeptDialogVisible = false;
              this.getdeptList(this.pageNum);
              let datime = new Date();
              eventBus.$emit("gengxin", datime);
            } else {
              console.log(res);
              this.$message.error(res.message);
            }
          });
        } else {
          this.$message.error("内容不完整");
        }
      });
    },
    editdepthandleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
  },
  data() {
    return {
      pageNum: {
        current: 1,
        size: 10,
        total: 0,
      },
      icons: "",
      adddeptDialogVisible: false,
      deldeptDialogVisible: false,
      editdeptDialogVisible: false,
      searchToggle: false,
      loading: true,
      downloadLoading: false,
      delDate: [],

      searchData: {
        name: "",
      },
      deptsForm: {
        dataScopeList: [],
        id: 0,
        level: 0,
        linkMan: "",
        linkPhone: "",
        name: "",
        pid: 0,
        status: 0,
      },
      tableData: [],
      tableData1: [],
      parentList: [],
      addData: {
        dataScopeList: [],
        level: "",
        linkMan: "",
        linkPhone: "",
        name: "",
        pid: "",
        status: 1,
      },
      rules: {
        name: [{ required: true, message: "必填", trigger: "blur" }],
        path: [{ required: true, message: "必填", trigger: "blur" }],
        icon: [{ required: true, message: "必填", trigger: "blur" }],
        linkMan: [{ required: true, message: "必填", trigger: "blur" }],
        linkPhone: [
          {
						required: true,
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: "手机号格式错误",
            trigger: ["blur", "change"],
          },
        ],
        // authStr: [{ required: true, message: "必填", trigger: "blur" }],
      },
      rules2: {
        phone: [
          {
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: "手机号格式错误",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    this.getdeptList();
    this.getdept1();
  },
};
</script>

<style lang="less" scoped>
.el-container {
  display: flex;
  justify-content: start;
  flex-direction: column;
  align-items: center;
}
.el-card {
  width: 100%;
}
.el-footer {
  align-self: start;
  margin-top: 1.5rem;
}
.c1 {
  display: flex;
  justify-content: start;
  margin-bottom: 1.5rem;
  width: 100%;
  .dBtn {
    margin-right: 1rem;
  }
}
.el-dialog {
  display: flex;
  justify-content: flex-start;
}
.btns {
  display: flex;
  justify-content: space-between;
}
.s1 {
  height: 0;
  margin-top: 2.5rem;
  display: flex;
  align-items: center;
}

.el-input /deep/.el-input__inner {
  height: 3.05rem;
}
.editform {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
  text-align: left;

  .el-input /deep/.el-input__inner {
    height: 3.05rem;
    font-size: 12px !important;
  }
}
.el-input /deep/.el-input__inner {
  height: 3.05rem;
  font-size: 12px !important;
}
.editform /deep/ .el-form-item {
  display: inline-block;
  margin-left: 1rem;

  width: 48%;
}
.editform /deep/ .el-form-item__content {
  height: 3.05rem;
}
.el-table /deep/ {
  font-size: 12px;
  padding: 2rem 0 0 2rem;
}
.el-switch /deep/ .el-switch__label * {
  font-size: 12px;
}
.el-table /deep/ thead {
  font-size: 12.5px;
  color: #909399;
  font-weight: 700;
}
</style>